package org.offsync.old.async

import java.nio.channels.SelectionKey
import org.offsync.util.NoOp

case class SelectionAttachment(
    val doAccept: () => Unit,
    val doConnect: () => Unit,
    val doRead: () => Unit,
    val doWrite: () => Unit) {
  def withOp(op: Int)(f: () => Unit): SelectionAttachment = {
    op match {
      case SelectionKey.OP_ACCEPT => this.copy(doAccept = f)
      case SelectionKey.OP_CONNECT => this.copy(doConnect = f)
      case SelectionKey.OP_READ => this.copy(doRead = f)
      case SelectionKey.OP_WRITE => this.copy(doWrite = f)
    }
  }
  
  def perform(readyOps: Int): Unit = {
    if ((readyOps & SelectionKey.OP_ACCEPT) != 0) return doAccept()
    if ((readyOps & SelectionKey.OP_CONNECT) != 0) return doConnect()
    if ((readyOps & SelectionKey.OP_READ) != 0) return doRead()
    if ((readyOps & SelectionKey.OP_WRITE) != 0) return doWrite()
  }
}

object SelectionAttachment extends SelectionAttachment(NoOp, NoOp, NoOp, NoOp)
